package cn.sh.yhk.controller;


import cn.sh.yhk.base.vo.BaseResponse;
import cn.sh.yhk.file.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    FileService fileService;
    //       private String uploadPath = "Y:\\西门茅王";
    @Value("${file.path}")
    private String uploadPath = "/imgfile/";


    @PostMapping("/uploadimg")
    @ResponseBody
    public BaseResponse<Integer> uploadimg(@RequestParam("file") MultipartFile file) throws IOException {
        File localFile = new File(uploadPath + file.getOriginalFilename());
        file.transferTo(localFile);
        int id = fileService.save(localFile);
        if (id > 0) {
            return BaseResponse.success(id);
        } else {
            localFile.deleteOnExit();
            return BaseResponse.fail(0);
        }
    }


    @GetMapping(value = "/image/{fileId}", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_PNG_VALUE})
    public ResponseEntity<Resource> getImage(@PathVariable("fileId") String fileId) throws MalformedURLException {
        File file = fileService.getFile(Integer.parseInt(fileId));
        Path imagePath = Paths.get(uploadPath + file.getName());
        Resource resource = new UrlResource(imagePath.toUri());
        if (resource.exists() || resource.isReadable()) {
            return ResponseEntity.ok().body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    }


}
